package com.ynet.middleground.approve.listener.contract;

import java.util.List;
import java.util.Optional;

import org.activiti.engine.delegate.DelegateExecution;
import org.activiti.engine.delegate.ExecutionListener;
import org.springframework.context.annotation.DependsOn;
import org.springframework.stereotype.Service;

import com.ynet.core.exception.BusinessException;
import com.ynet.middleground.approve.cmd.SpringContextUtils;
import com.ynet.middleground.approve.listener.BaseListener;
import com.ynet.middleground.approve.mq.producer.ContractTemplateProducer;

/**
 * @author liulx
 * @description 更新合约模板状态监听，主要用于合约模板的：激活、停用
 * @date 2020-04-28 14:55
 */
@DependsOn("springContextUtils")
@Service
public class UpdateContractTemplateStatusListener extends BaseListener implements ExecutionListener {

    /**
     * 引入发送合约模板的消费信息
     */
    protected ContractTemplateProducer producer = SpringContextUtils.getBean(ContractTemplateProducer.class);

    /**
     * 合约模板列表参数名, 对应的值的类型应该为：list {@link java.util.List<Integer>}
     */
    protected static final String TEMPLATE_IDS_KEY = "templateIds";

    /**
     * 状态标志，对应的值的类型应该为：String {@link java.lang.String} <br />
     * 合约模板状态码对应的值应该为: 1: 启用中, 2: 激活模板, 3: 停用模板
     */
    protected static final String TEMPLATE_STATUS_KEY = "templateStatus";

    @Override
    public void notify(DelegateExecution delegateExecution) {
        String channel = getChannel(delegateExecution);
        String operationUserId = getOperationUserId(delegateExecution);
        // 从流程中获取需要更新的模板 id 集合
        Object list = getObjectVariableInstance(delegateExecution, TEMPLATE_IDS_KEY);
        Optional.ofNullable(list)
            .orElseThrow(() -> new BusinessException("变量: " + TEMPLATE_IDS_KEY + " 不存在", "ECAP0506"));
        // 从流程中获取激活、停用标志
        Object templateStatus = getObjectVariableInstance(delegateExecution, TEMPLATE_STATUS_KEY);
        Optional.ofNullable(templateStatus)
            .orElseThrow(() -> new BusinessException("变量: " + TEMPLATE_STATUS_KEY + " 不存在", "ECAP0506"));

        if (list instanceof List<?>) {
            List<Integer> templateIds = (List<Integer>)list;
            producer.sendMessages(templateIds, templateStatus, channel, Integer.valueOf(operationUserId));
        }
    }

}
